package top.hcode.hoj.manager.coll;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.hcode.hoj.dao.collect.CollCreatedWorksDao;
import top.hcode.hoj.dao.org.OrgUserDao;
import top.hcode.hoj.pojo.entity.coll.CollCreatedWorks;
import top.hcode.hoj.pojo.vo.coll.CollCreatedWorksVO;
import top.hcode.hoj.service.admin.AdminCollCreatedWorksService;

import java.math.BigDecimal;

/**
 * @author orangej
 * @since 2025/1/21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ItechCollCreatedWorksManager {
    private final CollCreatedWorksDao createdWorksDao;
    private final OrgUserDao orgUserDao;
    private final AdminCollCreatedWorksService adminCollCreatedWorksService;

    public CollCreatedWorks deleteCreatedWorks(String uid, Long id) {
        String strId = String.valueOf(id);
        CollCreatedWorks works = createdWorksDao.getById(strId);
        if (works != null && works.getUserId().equals(uid)) {
            createdWorksDao.removeById(strId);
        }

        return works;
    }

    public CollCreatedWorks getCreatedWorks(String uid, String collId) {
        return createdWorksDao.getByUserIdAndCollId(uid, collId);
    }

    public CollCreatedWorksVO getCreatedWorksDetail(String uid, String collId) {
        return adminCollCreatedWorksService.getCollCreatedWorksDetail(uid, collId);
    }

    public CollCreatedWorksVO getCreatedWorksDetail(String id) {
        return adminCollCreatedWorksService.getCollCreatedWorksDetail(id);
    }

    public CollCreatedWorks saveCreatedWorks(CollCreatedWorks dto) {
        CollCreatedWorks dbo = getCreatedWorks(dto.getUserId(), dto.getCollId());
        if (dbo != null && dto.getId() == null) {
            dto.setId(dbo.getId()); // 只能有一个作品
        }

        if (dto.getId() == null) {
            dto.setUserName(orgUserDao.getRealNameByUid(dto.getUserId()));
            dto.setScore(BigDecimal.ZERO);
            dto.setScoreNum(0);
        }

        createdWorksDao.saveOrUpdate(dto);
        return dto;
    }


}
